<template>
  <div class="app-container">
    <div class="filter-container">
      <el-radio-group v-model="listQuery.state" class="filter-item" style="margin-left: 10px; ">
        <el-radio :label="0">全部</el-radio>
        <el-radio :label="1">待分配</el-radio>
        <el-radio :label="2">已分配</el-radio>
        <el-radio :label="3">已处理</el-radio>
      </el-radio-group>
      <el-select v-model="listQuery.type" style="margin-left: 10px;" class="filter-item" placeholder="请选择事件类型">
        <el-option
          v-for="item in options_type"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <el-select v-model="listQuery.method" style="margin-left: 10px;" class="filter-item" placeholder="请选择事件提交方式">
        <el-option
          v-for="item in options_method"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <el-input
        v-model="listQuery.handler"
        placeholder="请输入处理人姓名"
        style="width: 200px; margin-left: 10px"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <el-input
        v-model="listQuery.id"
        placeholder="请输入事件编号"
        style="width: 200px;margin-left: 10px"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <el-button v-waves style="margin-left: 10px;" class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column label="事件编号" prop="id" align="center" width="80" :class-name="getSortClass('id')">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="事件名称" align="center">
        <template slot-scope="{row}">
          <span> {{ getTypeValue(row.type)+"_"+row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="提交方式" align="center">
        <template slot-scope="{row}">
          <span> {{ getMethodValue(row.method) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="发生地点" align="center">
        <template slot-scope="{row}">
          <span><i class="el-icon-location" />{{ row.localeName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="发生时间" align="center">
        <template slot-scope="{row}">
          <span>{{ row.createTime | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="处理人" align="center">
        <template slot-scope="{row}">
          <span>{{ row.handler }}</span>
        </template>
      </el-table-column>
      <el-table-column label="事件状态" class-name="status-col" width="100">
        <template slot-scope="{row}">
          <el-tag :type="row.state | statusFilter">
            {{ getStateValue(row.state) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button type="info" size="mini" @click="handleUpdate(row)">
            详情
          </el-button>
          <el-button v-if="row.state==1" size="mini" type="success" @click="handleDistribute(row)">
            事件分配
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.pageNum"
      :limit.sync="listQuery.pageSize"
      @pagination="getList"
    />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="110px"
        style="width: 400px; margin-left:50px;"
      >
        <el-form-item v-if="['update','create'].includes(dialogStatus)" label="事件名称" prop="username">
          <el-input v-model="temp.name" placeholder="请输入事件名称" :readonly="['update'].includes(dialogStatus)" />
        </el-form-item>
        <el-form-item v-if="['update','create'].includes(dialogStatus)" label="发生地点" prop="nickName">
          <el-input v-model="temp.localeName" :readonly="['update'].includes(dialogStatus)" placeholder="请输入发生地点" />
        </el-form-item>
        <el-form-item v-if="['update','create'].includes(dialogStatus)" label="事件状态">
          <el-select v-model="temp.state" class="filter-item" :disabled="['update'].includes(dialogStatus)" placeholder="请选择事件状态">
            <el-option v-for="item in options_state" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="['update'].includes(dialogStatus)" label="发生时间" prop="createTime">
          <el-date-picker v-model="temp.occurrenceTime" type="datetime" :readonly="['update'].includes(dialogStatus)" />
        </el-form-item>
        <el-form-item v-if="['update','create'].includes(dialogStatus) && temp.occurUrl.length>0" label="问题图片">
          <el-badge :value="temp.occurUrl.length" class="item" type="primary">
            <el-image
              style="width: 50px; height: 50px"
              :src="temp.occurUrl[0]"
              :preview-src-list="temp.occurUrl"
            >
              <div slot="error" class="image-slot">
                <i class="el-icon-picture-outline" />
              </div>
            </el-image>
          </el-badge>
        </el-form-item>
        <el-form-item v-if="['update','create'].includes(dialogStatus)" label="问题备注">
          <el-input v-model="temp.remark" type="textarea" />
        </el-form-item>
        <el-form-item v-if="['update','create'].includes(dialogStatus)" label="处理人" prop="phoneNum">
          <el-input v-model="temp.handler" :readonly="['update'].includes(dialogStatus)" placeholder="请输入处理人" />
        </el-form-item>
        <el-form-item v-if="['update','create'].includes(dialogStatus)" label="处理人手机号" prop="phoneNum">
          <el-input v-model="temp.phoneNum" :readonly="['update'].includes(dialogStatus)" placeholder="请输入处理人手机号" />
        </el-form-item>
        <el-form-item v-if="['update'].includes(dialogStatus)" label="处理时间" prop="createTime">
          <el-date-picker v-model="temp.processTime" type="datetime" :readonly="['update'].includes(dialogStatus)" />
        </el-form-item>
        <el-form-item v-if="['update','create'].includes(dialogStatus)" label="处理备注">
          <el-input v-model="temp.comment" :readonly="['update'].includes(dialogStatus)" type="textarea" />
        </el-form-item>
        <el-form-item v-if="['update','create'].includes(dialogStatus) && temp.handleUrl.length>0" label="处理图片">
          <el-badge :value="temp.handleUrl.length" class="item" type="primary">
            <el-image
              style="width: 50px; height: 50px"
              :src="temp.handleUrl[0]"
              :preview-src-list="temp.handleUrl"
            >
              <div slot="error" class="image-slot">
                <i class="el-icon-picture-outline" />
              </div>
            </el-image>
          </el-badge>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确认
        </el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="dialogPvVisible" title="事件分配">
      <el-form ref="dataFormHandler" :rules="rulesHandler" :model="tempHandler" label-position="left" label-width="100px" style="width: 400px; margin-left:50px;">
        <el-form-item label="处理人" prop="inspectorId">
          <el-select v-model="valueHandler" filterable placeholder="请选择" @change="handleChange">
            <el-option
              v-for="item in handlers"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confirmData()">确认</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { listEvent, modifyEvent } from '@/api/event/event-handle'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { listInspector } from '../../../api/info/personnel'

const calendarTypeOptions = [
  { key: 'CN', display_name: 'China' },
  { key: 'US', display_name: 'USA' },
  { key: 'JP', display_name: 'Japan' },
  { key: 'EU', display_name: 'Eurozone' }
]

// arr to obj, such as { CN : "China", US : "USA" }
const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})

export default {
  name: 'EventHandle',
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        1: 'info',
        2: 'primary',
        3: 'success'
      }
      return statusMap[status]
    },
    typeFilter(type) {
      return calendarTypeKeyValue[type]
    }
  },
  data() {
    return {
      handlers: [],
      options_state: [
        {
          value: 1,
          label: '待分配'

        },
        {
          value: 2,
          label: '待处理'

        },
        {
          value: 3,
          label: '已处理'
        }
      ],
      options_type: [
        {
          value: '',
          label: '全部类型'

        },
        {
          value: 1,
          label: '汽车占道违停'

        },
        {
          value: 2,
          label: '电动车占到违停'
        }
      ],
      options_method: [
        {
          value: '',
          label: '全部方式'

        },
        {
          value: 1,
          label: '固定设备'

        },
        {
          value: 2,
          label: '移动设备'
        },
        {
          value: 3,
          label: '巡查人员'
        }
      ],
      valueHandler: '',
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        pageNum: 1,
        pageSize: 10,
        handler: '',
        state: 0,
        type: '',
        method: ''
      },
      importanceOptions: [1, 2, 3],
      calendarTypeOptions,
      sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
      statusOptions: [{ key: '1', text: '待处理' }, { key: '0', text: '已处理' }, { key: '2', text: '待分配' }],
      showReviewer: false,
      tempHandler: {
        id: '',
        inspectorId: '',
        state: '2'
      },
      temp: {
        id: '',
        occurrenceTime: '',
        processTime: '',
        phoneNum: '',
        handler: '',
        type: '',
        method: '',
        remark: '',
        occurUrl: [],
        handleUrl: [],
        localeName: '',
        comment: '',
        state: '',
        name: '',
        urls: [],
        urls_r: []
      },
      dialogFormVisible: false,
      dialogFormVisible1: true,
      dialogStatus: '',
      textMap: {
        update: '处理',
        create: ' 添加'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {},
      rulesHandler: {},
      downloadLoading: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 获取事件状态
    getStateValue(status) {
      const statusMap = {
        1: '待分配',
        2: '已分配',
        3: '已处理'
      }
      return statusMap[status]
    },
    // 事件类型
    getTypeValue(status) {
      const statusMap = {
        1: '汽车占道违停',
        2: '电动车占到违停'
      }
      return statusMap[status]
    },
    // 事件提交方式
    getMethodValue(status) {
      const statusMap = {
        1: '固定设备',
        2: '移动设备',
        3: '巡查人员'
      }
      return statusMap[status]
    },
    handleChange(value) {
      this.tempHandler.inspectorId = value
    },
    getList() {
      this.listLoading = true
      listEvent(this.listQuery).then(response => {
        this.list = response.data.list
        this.total = response.data.total
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.pageNum = 1
      this.getList()
    },
    handleDistribute(row) {
      this.listLoading = true
      this.rulesHandler = {
        inspectorId: [{ required: true, trigger: ['blur', 'change'], message: '处理人不能为空' }]
      }
      this.temp = Object.assign({}, row) // copy obj
      this.temp.timestamp = new Date(this.temp.timestamp)
      this.valueHandler = ''
      this.tempHandler.id = row.id
      this.tempHandler.inspectorId = ''
      listInspector({}).then(response => {
        const handlersArr = []
        const { data } = response
        const result = data.list || []
        result.forEach(item => {
          handlersArr.push({
            value: item.id,
            label: item.name + '_' + item.phoneNum
          })
        })
        this.handlers = handlersArr
        this.listLoading = false
      })
      this.dialogStatus = 'distribute'
      this.dialogPvVisible = true
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        id: '',
        occurrenceTime: '',
        processTime: '',
        phoneNum: '',
        handler: '',
        type: '',
        method: '',
        remark: '',
        occurUrl: [],
        handleUrl: [],
        localeName: '',
        comment: '',
        state: '',
        name: '',
        urls: [],
        urls_r: []
      }
    },
    handleUpdate(row) {
      this.rules = {}
      this.temp = Object.assign({}, row) // copy obj
      this.temp.timestamp = new Date(this.temp.timestamp)
      this.temp.name = this.getTypeValue(this.temp.type) + '_' + this.temp.id
      const urls = []
      if (this.temp.urlA !== '') {
        urls.push(this.temp.urlA)
      }
      if (this.temp.urlB !== '') {
        urls.push(this.temp.urlB)
      }
      if (this.temp.urlC !== '') {
        urls.push(this.temp.urlC)
      }
      this.temp.urls = urls

      const urls_r = []
      if (this.temp.urlX !== '') {
        urls_r.push(this.temp.urlX)
      }
      if (this.temp.urlY !== '') {
        urls_r.push(this.temp.urlY)
      }
      if (this.temp.urlZ !== '') {
        urls_r.push(this.temp.urlZ)
      }
      this.temp.urls_r = urls_r
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    confirmData() {
      this.$refs['dataFormHandler'].validate((valid) => {
        if (valid) {
          this.listLoading = true
          modifyEvent(this.tempHandler).then(response => {
            const index = this.list.findIndex(v => v.id === this.temp.id)
            this.temp = Object.assign({}, response.data) // copy obj
            this.list.splice(index, 1, this.temp)
            this.listLoading = false
            this.$notify({
              title: '成功',
              message: '分配成功',
              type: 'success',
              duration: 2000
            })
            this.dialogPvVisible = false
          })
        }
      })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
        const filterVal = ['timestamp', 'title', 'type', 'importance', 'status']
        const data = this.formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-list'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    }
  }
}
</script>
